<template>
	<view class="content">
		<wd-tabs v-model="active" animated swipeable @change="tabsChange">
			<block v-for="item in navList" :key="item.name">
				<wd-tab :title="item.title" :name="item.name">
					<scroll-view scroll-y="true" @scrolltolower="handleScroll(item.name)" style="height: 100vh;">
						<view class="main">
							<wd-gap height="85rpx"></wd-gap>

							<view class="alone" v-for="article in articList[item.name]" :key="article._id"
								@click="gotoDetail(article._id)">
								<!--blog-item :blog="article" @updateList="updateList(article._id)" /-->
								<div class="card">
									<!-- title 部分 -->
									<div class="blog-title">
										<img :src="article.author.img" width="40" height="40" alt="" />
										<div class="user-name">
											{{ article.author.name }}
										</div>
										<div class="create-time">
											{{ getTimeAgo(article.publishedAt) }}
										</div>
									</div>

									<!-- blog body 部分 -->
									<div class="blog-body">
										<div class="body-title">{{ article.title }}</div>
										<div class="body-tip" style="white-space: pre-wrap;">
											{{ article.summary }}
										</div>

										<div class="body-image">
											<!--图像支持-->
											<img v-for="(imageUrl, index) in blog.picurls" :key="guid()" :src="imageUrl"
												alt="blog-image" class="image-item" @click.stop="preview(index)" />
										</div>
									</div>
									<!-- 点赞评论 部分 -->
									<div class="blog-footer">
										<div class="operation-icon">
											<wd-icon name="chat1" size="36rpx"></wd-icon>
											<div>{{ blog.view_count }}</div>
										</div>
										<div class="operation-icon" :class="article.isLike ? 'active' : ''"
											@click.stop="onLike(article._id)">
											<wd-icon name="thumb-up" size="34rpx"></wd-icon>
											<div>{{ article.like_count ? article.like_count : "点赞" }}</div>
										</div>
									</div>
								</div>
							</view>
							<view class="load-text">
								{{ loadText[item.name] }}
							</view>
						</view>
					</scroll-view>
				</wd-tab>
			</block>
		</wd-tabs>
	</view>
</template>
<script>
	export default {
	    data() {
	        return {
	            uid: '',
	            hasNavigated: false,
	            active: 'tab4', // 默认选中的 tab
	            navList: [
	                { title: '接妆', name: 'tab1' },
	                { title: '接毛', name: 'tab2' },
	                { title: '摄影', name: 'tab3' },
	                { title: '票代', name: 'tab4' },
	                { title: '道具师', name: 'tab5' }
	            ], // 导航列表
	            articList: {
	                tab1: [], // Tab 1 的文章列表
	                tab2: [], // Tab 2 的文章列表
	                tab3: [], // Tab 3 的文章列表
	                tab4: [], // Tab 4 的文章列表
	                tab5: []  // Tab 5 的文章列表
	            },
	            pageNo: {
	                tab1: 1,
	                tab2: 1,
	                tab3: 1,
	                tab4: 1,
	                tab5: 1
	            }, // 每个 tab 的页码
	            pageSize: 8,
	            isLoading: false, // 防止多次请求
	            loadText: {
	                tab1: '加载更多...',
	                tab2: '加载更多...',
	                tab3: '加载更多...',
	                tab4: '加载更多...',
	                tab5: '加载更多...'
	            },
	            isMore: {
	                tab1: true,
	                tab2: true,
	                tab3: true,
	                tab4: true,
	                tab5: true
	            }, // 判断是否还有更多数据
	            blog: {
	                _id: 1,
	                avatar_file: { url: 'default-avatar.png' },
	                nickname: 'John Doe',
	                username: 'johndoe',
	                last_modify_date: '2025-01-24T00:00:00',
	                view_count: 10,
	                like_count: 5,
	                isLike: true,
	                picurls: [],
	                title: '',
	                excerpt: 'This is an excerpt of the blog post.',
	            },
				url:null,
	            defalutAvatar: 'default-avatar.png',
	            isShow: true
	        };
	    },
	    mounted() {
	        if (!this.hasNavigated) {
	            this.hasNavigated = true; // 设置跳转标志
	            this.uid = uni.getStorageSync('uid');
	            if (this.uid === '') {
	                uni.reLaunch({
	                    url: '/pages/login/login'
	                });
	            }
	        }
	        const currentVersion = "1.1.4";
	        uni.request({
	            url: 'http://14.103.233.198:9999/update', // 替换成你的API地址
	            method: 'GET',
	            data: {},
	            success(res) {
	                console.log(currentVersion, res.data.version);
	                if (res.data.version > currentVersion) {
	                    uni.showModal({
	                        title: '新版本提示',
	                        content: '发现新版本，是否更新？',
	                        success: function(result) {
	                            if (result.confirm) {
	                                plus.runtime.openURL(res.data.updateUrl, function(res) {
	                                    console.log(res);
	                                });
	                            }
	                        }
	                    });
	                }
	            }
	        });
	        this.loadPosts(this.active); // 页面加载时初始化第一个 tab 的数据
	    },
		methods: {
			guid() {
			        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			            const r = Math.random() * 16 | 0;
			            const v = c === 'x' ? r : (r & 0x3 | 0x8);
			            return v.toString(16);
			        });
			    },
			async onLike(id) {
				this.uid = uni.getStorageSync('uid');
				const article = this.findArticleById(id);
				if (article.isLike) {
					const res = await new Promise((resolve, reject) => {
						uni.request({
							url: 'http://14.103.233.198:9999/unlike', // 替换为实际的接口
							method: 'GET',
							data: {
								uid: this.uid,
								articles_id: id,
							},
							success: (response) => resolve(response),
						});
					});
				} else {
					const res = await new Promise((resolve, reject) => {
						uni.request({
							url: 'http://14.103.233.198:9999/like', // 替换为实际的接口
							method: 'GET',
							data: {
								uid: this.uid,
								articles_id: id,
							},
							success: (response) => resolve(response),
						});
					});
				}
				uni.reLaunch({
				  url: '/pages/tabbar/tabbar-1/tabbar-1'
				});
			
			
			},
			findArticleById(id) {
				for (const tab in this.articList) {
					const article = this.articList[tab].find(item => item._id === id);
					if (article) {
						return article;
					}
				}
				return null;
			},
			getTimeAgo(date) {
				const now = new Date();

				// 确保传入的时间是本地时间
				const inputDate = new Date(date);

				// 获取两个时间的时间戳
				const diffInMilliseconds = now.getTime() - inputDate.getTime();
				const diffInMillisecondsWith8Hours = diffInMilliseconds + (8 * 60 * 60 * 1000);
				const seconds = Math.floor(diffInMillisecondsWith8Hours / 1000);
				const minutes = Math.floor(seconds / 60);
				const hours = Math.floor(minutes / 60);
				const days = Math.floor(hours / 24);
				if (days > 0) return `${days}天前`;
				if (hours > 0) return `${hours}小时前`;
				if (minutes > 0) return `${minutes}分钟前`;
				return `${seconds}秒前`;
			},
			// 获取文章数据
			async loadPosts(tabName) {
				this.uid = uni.getStorageSync('uid');
				//if (this.isLoading || !this.isMore[tabName]) return; // 防止重复加载

				this.isLoading = true;
				this.loadText[tabName] = '正在加载...';

				try {
					// 使用 uni.request 获取文章数据
					const res = await new Promise((resolve, reject) => {
						uni.request({
							url: 'http://14.103.233.198:9999/articles', // 替换为实际的接口
							method: 'GET',
							data: {
								page: this.pageNo[tabName],
								page_size: this.pageSize,
								tab: tabName,
								uid: this.uid,
							},
							success: (response) => resolve(response),
							fail: (error) => reject(error),
						});
					});

					// Check if 'articles' is defined and is an array
					const articles = res.data.data.articles;
					console.log(articles);
					if (articles.length === 0) {
						this.isMore[tabName] = false;
					}

					// Update article list
					this.articList[tabName].push(...articles);

					// Increment page number
					this.pageNo[tabName] += 1;

					// Check if there are more articles based on the response
					if (res.data.message === "没有更多的帖子了" || articles.length < this.pageSize) {
						this.isMore[tabName] = false;
					}

				} catch (error) {
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					this.isLoading = false;
					this.loadText[tabName] = this.isMore[tabName] ? '加载更多...' : '没有更多内容';
					this.$nextTick(() => {
						this.$forceUpdate(); // 强制触发 Vue 更新视图
					});
				}
			},

			// 切换 tab 时调用
			async tabsChange(tabName) {
				this.loadPosts(tabName.name);
				//if (this.articList[tabName].length === 0) {
				//  this.loadPosts(tabName);  // 初次加载时触发
				//}
			},

			// 滚动到底部时触发加载更多
			handleScroll(tabName) {
				if (this.isMore[tabName] && !this.isLoading) {
					this.loadPosts(tabName);
				}
			},

			// 跳转到文章详情页
			gotoDetail(articleId) {
				uni.navigateTo({
					url: `/pages/postDetail/postDetail?id=${articleId}`
				});
			},
		},

		mounted() {
			this.loadPosts(this.active); // 页面加载时初始化第一个 tab 的数据
		}
	};
</script>

<style scoped>
	.content {
		padding: 20px;
	}

	.main {
		padding: 10px;
	}

	.alone {
		margin-bottom: 10px;
	}

	.load-text {
		text-align: center;
		padding: 10px;
		color: #888;
		font-size: 14px;
	}
</style>
<style lang="scss" scoped>
	.card {
		border: 1px solid #ccc;
		border-radius: 8px;
		overflow: hidden;
		margin: 16px;
		background-color: white;
	}

	.blog-title {
		display: flex;
		align-items: center;
		padding: 12px;
		border-bottom: 1px solid #f0f0f0;
	}

	.blog-title img {
		border-radius: 50%;
		margin-right: 10px;
	}

	.user-name {
		font-size: 14px;
		font-weight: bold;
	}

	.create-time {
		font-size: 12px;
		color: #888;
	}

	.more-action {
		margin-left: auto;
		font-size: 18px;
		cursor: pointer;
	}

	.blog-body {
		padding: 12px;
	}

	.body-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 8px;
	}

	.body-tip {
		font-size: 14px;
		color: #777;
		margin-bottom: 12px;
	}

	.body-image img {
		width: 100%;
		height: auto;
		margin-bottom: 8px;
	}

	.blog-footer {
		display: flex;
		padding: 12px;
		border-top: 1px solid #f0f0f0;
	}

	.operation-icon {
		display: flex;
		align-items: center;
		margin-right: 20px;
		font-size: 14px;
	}

	.operation-icon .icon {
		margin-right: 5px;
	}

	.operation-icon.active {
		color: #007aff;
	}

	.wd-tabs {
		margin-top: -20px;
		/* 根据需要调整值 */
	}

	.scroll-view {
		margin-top: 0;
		/* 设置为0，去除顶部间隙 */
		padding-top: 0;
	}

	@import "@/pages/tabbar/tabbar-1/tabbar-1.scss"
</style>